/* Utility scripts for Pardus Sector Tool
 * (C) Yassen 2010
 *
 * sector.js
 * Defines functions for sectors.
 *
 * Functions:
 * Export(id)
 * Import(id, code)
 * Draw(id)
 * Clear(id)
 */

Global.CurrentTile = { cell: null, x: null, y: null, id: null, tile: null };

Utility.Sector.Name = function()
{
  return Global.DisplayedSector.name;
}

Utility.Sector.Export = function()
{
  return ImportModules["Current"].ExportSector(Global.DisplayedSector);
}

Utility.Sector.Import = function(code)
{
  var regex = new RegExp('"version":([0-9]*)');
  var version = regex.exec(code)[1] * 1;
  return ImportModules[version].ImportSector(code);
}

Utility.Sector.MapToTiles = function(code)
{
  var parts = code.split("|");
  var dim = parts[1].split("X");
  var width = dim[0] * 1;
  var height = dim[1] * 1;
  var data = parts[0];

  var tiles = [];
  var i = 0;

  for (var y = 0; y <= height; y++)
  {
    for (var x = 0; x <= width; x++)
    {
      tiles.push(new Tile(i, AbbrToTileType(data[i]), x, y, false));
      i++;
    }
  }

  return tiles;
}

Global.CachedMaps["PI 4-669"] = Utility.Sector.MapToTiles("bbbeeebbbbbbefebbbbbbeeebbbbbbbebbeebbeeeeeeebeeffffeeeeffeeeebeefeebeeebeeebbeeebbeebbbee|8X9");

Sector.prototype.toHTML = function()
{
  var html = "<table class='map' oncontextmenu='return false;'><tr><th></th>";

  var width = this.tiles[this.tiles.length - 1].x + 1;  // Last element is the extent
  var height = this.tiles[this.tiles.length - 1].y + 1;

  for (var x = 0; x < width; x++)
    html += "<th width='32px'><img src='./images/blank.jpg' height='0px' width='32px' /><br />" + x + "</th>";

  var id = 0;

  for (var y = 0; y < height; y++)
  {
    row = "<tr><th valign='middle'><img src='./images/blank.jpg' height='32px' width='0px' style='float: left;' />" + y + "</th>";

    for (var x = 0; x < width; x++)
    {
      var tile = this.tiles[id];
      row += "<td class='" + TileTypeToAbbr(tile.type) + "' ";

      Global.CurrentTile = { html: row, x: x, y: y, id: id, type: tile.type };
      EventSink.fireEvent("TileCreated");
      row = Global.CurrentTile.html;

      row += "</td>";
      id++;
    }

    row += "</tr>";
    html += row;
  }

  return html;
}

Utility.Sector.GetBlank = function(name, map)
{
  return new Sector(name, [], [], [], [], [], map);
}